package com.atguigu.gmall.list.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.service.ListService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 搜索上下架相关监听器
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class ListListener {
    @Autowired
    private ListService listService;
    //上架
    @RabbitListener(bindings = @QueueBinding(exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, durable = "true", autoDelete = "false"),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void receiverOnsaleMessage(Long skuId, Message message, Channel channel) {
        System.out.println("接收到的 " + skuId);
        //标准应答参考service-mq的ConsumerListener
        try {
            //上架 添加ES索引库
            listService.onSale(skuId);
            //应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //下架
    @RabbitListener(bindings = @QueueBinding(exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, durable = "true", autoDelete = "false"),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void receiverCancelsaleMessage(Long skuId, Message message, Channel channel) {
        System.out.println("接收到的 " + skuId);
        //标准应答参考service-mq的ConsumerListener
        try {
            //下架 删除ES索引库
            listService.cancelSale(skuId);
            //应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
